package com.helper.dream.a361phonehelper.utils;

import com.helper.dream.a361phonehelper.MyApplication;

import java.io.File;
import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by LamYu on 16/12/20/0020.
 */

public class HttpClientUtil {

    public static OkHttpClient initClient() {
        Interceptor interceptor = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetUtils.hasNetwork(MyApplication.getInstance())){
                    request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                okhttp3.Response response = chain.proceed(request);
                if (NetUtils.hasNetwork(MyApplication.getInstance())){
                    int maxAge = 60 * 60;
                    response.newBuilder()
                            .removeHeader("Pragma")
                            .header("Cache-Control","public,max-age="+maxAge)
                            .build();
                }else {
                    int maxScale = 60 * 60 * 24 * 7;
                    response.newBuilder().removeHeader("Pragma")
                            .header("Cache-Control","public, only-if-cached, max-stale="+maxScale)
                            .build();
                }
                return response;
            }
        };
        File cacheFile = new File(MyApplication.getInstance().getExternalCacheDir(),"mycache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 20);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .addInterceptor(interceptor).cache(cache).build();
        return client;
    }
}
